package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.Exception.UserUniqueException;
import com.atguigu.gulimall.member.Vo.MemberVo;
import com.atguigu.gulimall.member.Vo.SocialUser;
import com.atguigu.gulimall.member.Vo.UserVo;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.service.MemberLevelService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void registMember(UserVo userVo) {
        MemberEntity memberEntity = new MemberEntity();

        // 用户的 默认等级
        MemberLevelEntity levelEntity = memberLevelService.getDefaultLevel();
        memberEntity.setLevelId(Long.valueOf(levelEntity.getDefaultStatus()));

        // 在插入 会员表时还得校验 用户唯一性
        checkPhoneUnique(userVo.getPhone());
        checkUsernamUnique(userVo.getUserName());

        memberEntity.setUsername(userVo.getUserName());
        memberEntity.setMobile(userVo.getPhone());

        // 密码采用盐值加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(userVo.getPassword());
        memberEntity.setPassword(encode);

        save(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws UserUniqueException {
        int count = this.count(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new UserUniqueException("手机号已存在");
        }
    }

    @Override
    public void checkUsernamUnique(String userName) throws UserUniqueException {
        int count = this.count(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0) {
            throw new UserUniqueException("用户已存在已存在");
        }
    }

    @Override
    public MemberEntity login(MemberVo memberVo) {
        // 账号校验
        String loginacct = memberVo.getLoginacct();
        MemberEntity entity = this.getOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if (entity == null) {
            return null;
        } else {
            // 取出数据库的密码
            String passwordDb = entity.getPassword();
            // 进行加密验证   md5加密验证
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean flag = encoder.matches(memberVo.getPassword(), passwordDb);
            if (flag == true) {
                return entity;
            } else {
                return null;
            }
        }
    }


    /**
     * 实现社交登录
     *
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity socialLogin(SocialUser socialUser) throws Exception {
        // 先判断 是否注册过
        MemberEntity entity = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUser.getUid()));

        if (entity != null) {
            // 刷新 登录用的 token 以及过期时间  注意重复登录 会刷新 token    uid一致保持不变
            MemberEntity update = new MemberEntity();
            update.setId(entity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            this.updateById(update);

            entity.setExpiresIn(socialUser.getExpires_in());
            entity.setAccessToken(socialUser.getAccess_token());

            return entity;
        } else {
            // 第一次登录 注册 用户
            MemberEntity register = new MemberEntity();

            // 通过获取的令牌和 uid去 第三方获取  可以获取第三方的公开信息
            Map<String, String> query = new HashMap<>();
            query.put("access_token", socialUser.getAccess_token());
            query.put("uid", socialUser.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);

            if (response.getStatusLine().getStatusCode() == 200) {
                //查询成功
                String json = EntityUtils.toString(response.getEntity());


                JSONObject jsonObject = JSON.parseObject(json);
                String name = jsonObject.getString("name");
                String gender = jsonObject.getString("gender");
                String profileImageUrl = jsonObject.getString("profile_image_url");

                register.setNickname(name);
                register.setGender("m".equals(gender) ? 1 : 0);
                register.setHeader(profileImageUrl);
                register.setCreateTime(new Date());

                // 这里是获取 注册时关键的 信息
                register.setSocialUid(socialUser.getUid());
                register.setExpiresIn(socialUser.getExpires_in());
                register.setAccessToken(socialUser.getAccess_token());
                save(register);
            }
            return register;
        }
    }
}